package com.hh.base.log

import android.annotation.SuppressLint
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetSocketAddress
import java.text.SimpleDateFormat
import java.util.Date

/**
 * Create By hHui on 2025/4/3 16:35
 *
 * @description
 */
class NetLog(private val host: String, private val port: Int) : ILog {
    private val xmlLogString = "<log level=\"%s\" app=\"%s\" thread=\"%s\" time=\"%s\" logger=\"%s\"><![CDATA[%s]]></log>"

    override fun d(tag: String, msg: String?, t: Throwable?) {
        print("DEBUG", tag, msg)
    }

    override fun i(tag: String, msg: String?, t: Throwable?) {
        print("INFO", tag, msg)
    }

    override fun w(tag: String, msg: String?, t: Throwable?) {
        print("WARN", tag, msg)
    }

    override fun e(tag: String, msg: String?, t: Throwable?) {
        print("ERROR", tag, msg)
    }

    override fun v(tag: String, msg: String?, t: Throwable?) {
        print("INFO", tag, msg)
    }

    override fun dispose() {
    }

    @SuppressLint("CheckResult")
    private fun print(level: String, tag: String, msg: String?) {
        Flowable.create(FlowableOnSubscribe<Boolean> {
            val sendMsg = String.format(
                xmlLogString, level, "fais6", Thread.currentThread().id.toString(), Date().toShowStr(), tag, msg
            )
            val ds = DatagramSocket()
            val sendBytes = sendMsg.toByteArray()
            val dp = DatagramPacket(sendBytes, sendBytes.size, InetSocketAddress(host, port))
            ds.send(dp)
            ds.close()
            it.onNext(true)
        }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.single()).observeOn(AndroidSchedulers.mainThread()).subscribe({

        }, {

        })
    }


    private fun Date.toShowStr(): String {
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this)
    }
}